<template>
  <div id="issueApplyEditDiv">
    <div class="form">
      <el-form ref="issueFormRef" v-loading="aloading" :model="issueForm" :rules="issueFormRule" class="form-input-m" label-width="100px" inline-message>
        <el-row>
          <el-col :span="spNum">
            <el-form-item prop="issueClassifyName" label="问题分类">
              <el-input type="text" v-model="issueForm.issueClassifyName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="issueTypeName" label="问题类型">
              <el-input type="text" v-model="issueForm.issueTypeName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item label="分派人" prop="assignId">
              <el-select v-model="issueForm.assignId" filterable placeholder="分派人" style="width:200px">
                <template v-for="(dot,idx) in userList" :key="idx">
                  <el-option :label="dot.realname" :value="dot.id"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="customerName" label="客户名称">
              <el-input type="text" v-model="issueForm.customerName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item label="项目经理" prop="projectManagerId">
              <el-select v-model="issueForm.projectManagerId" filterable placeholder="项目经理" style="width:200px">
                <template v-for="(dot,idx) in userList" :key="idx">
                  <el-option :label="dot.realname" :value="dot.id"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="contactorName" label="联系人">
              <el-input type="text" v-model="issueForm.contactorName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="contactorTel" label="联系电话">
              <el-input type="text" v-model="issueForm.contactorTel" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="expectFinishTime" label="期望完成时间">
              <el-date-picker v-model="issueForm.expectFinishTime" type="date" placeholder="期望完成时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="severity" label="严重程度">
              <el-select v-model="issueForm.severity" placeholder="请选择严重程度" style="width:200px">
                <el-option v-for="(status) in issueSeverityList" :key="status.code" :label="status.name" :value="status.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="priority" label="优先级">
              <el-select v-model="issueForm.priority" placeholder="请选择优先级" style="width:200px">
                <el-option v-for="(status) in issuePriorityList" :key="status.code" :label="status.name" :value="status.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="spNum">
            <el-form-item prop="issueSource" label="问题来源">
              <el-input type="text" v-model="issueForm.issueSource" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum*3">
            <el-form-item prop="title" label="问题标题">
              <el-input v-model="issueForm.title" type="text" placeholder="请输入问题标题" style="width: 486px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spNum*3">
            <el-form-item prop="description" label="问题描述">
              <CkEditor ref="refCkEditor" :value="issueForm.description" folderId="system123" @editorInput="(val)=>issueForm.description=val" style="width: 486px;" />
            </el-form-item>
          </el-col>
          <el-col :span="spNum*2" style="margin-left:100px">
            <el-button type="warning" :loading="saving" @click="editForm('issueFormRef')">暂存</el-button>
            <el-button type="primary" :loading="submiting" @click="confirmForm('issueFormRef')">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import CkEditor from '@/components/CkEditor.vue';
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑

let store = AppStore();
let sltIssueApply: any = {};

let { proxy }: any = getCurrentInstance();
let spNum = 8;
let saving = ref(false);
let submiting = ref(false);
let aloading = ref(false);
let userList: any = reactive([]);
let issueSeverityList: any = reactive([]); //选择字典
let issuePriorityList: any = reactive([]);
let issueForm = reactive({
  id: null,
  issueClassify: '',
  issueClassifyName: '',
  issueType: '',
  issueTypeName: '',
  assignId: '',
  severity: '',
  priority: '',
  issueSource: '',
  customerId: '',
  customerName: '',
  projectManagerId: '',
  projectManagerName: '',
  contactorName: '',
  contactorTel: '',
  title: '',
  description: '',
  status: 0,
  orgId: '',
  expectFinishTime: '',
  submitter: '',
  submitTime: ''
});
// 最左侧动态表弹框表单校验
let issueFormRule = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    }
  ]
};

defineExpose({ initPage });
function initPage(row: any) {
  getDictItemsList(); //批量获取字典
  getUserOptions();
  sltIssueApply = row.value;
  setIssueForm(sltIssueApply);
}

// onMounted(() => {
//   getDictItemsList(); //批量获取字典
//   getUserOptions();
// });

async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['issueSeverity', 'issuePriority'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'issueSeverity');
  issueSeverityList.push(...severityType.detailDataList);

  const priorityType = dictTreeTypeItems.data.find((item) => item.code === 'issuePriority');
  issuePriorityList.push(...priorityType.detailDataList);
}

function getUserOptions() {
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      userList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取所有用户选项 (下拉框)失败', VxeNotifyType.error);
    });
}

function editForm(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    saveForm(formName, 0);
  });
}
function confirmForm(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    proxy
      .$confirm('确定提交？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        saveForm(formName, 5);
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  });
}
function saveForm(formName: any, status) {
  if (status == 0) {
    saving.value = true;
  } else if (status == 5) {
    submiting.value = true;
  }
  let obj: any = {};
  let url = '';

  obj = {
    id: issueForm.id,
    issueClassify: issueForm.issueClassify,
    issueClassifyName: issueForm.issueClassifyName,
    issueType: issueForm.issueType,
    issueTypeName: issueForm.issueTypeName,
    assignId: issueForm.assignId,
    severity: issueForm.severity,
    priority: issueForm.priority,
    issueSource: issueForm.issueSource,
    customerId: issueForm.customerId,
    customerName: issueForm.customerName,
    projectManagerId: issueForm.projectManagerId,
    projectManagerName: issueForm.projectManagerName,
    contactorName: issueForm.contactorName,
    contactorTel: issueForm.contactorTel,
    title: issueForm.title,
    description: issueForm.description,
    status: status,
    orgId: store.userInfo.orgId,
    expectFinishTime: isEmpty(issueForm.expectFinishTime) ? '' : moment(new Date(issueForm.expectFinishTime)).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    submitter: store.userInfo.id,
    submitTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  };
  if (issueForm.id) {
    url = '/api/wk/wkIssueApply/editIssueApply';
  } else {
    url = '/api/wk/wkIssueApply/addIssueApply';
  }
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (status === '0') {
          VxeMessage('暂存成功', VxeNotifyType.success);
        } else if (status === '5') {
          VxeMessage('提交成功', VxeNotifyType.success);
        }

        issueForm.id = res.data.id;
        proxy.$emit('saveIssueApplySuccess',issueForm.id);
      } else {
        VxeMessage('更新失败', VxeNotifyType.error);
      }
      saving.value = false;
      submiting.value = false;
    })
    .catch((err: any) => {
      VxeMessage('更新失败', VxeNotifyType.error);
    });
}

function setIssueForm(data: any) {
  issueForm.id = data.id;
  issueForm.issueClassify = data.issueClassify;
  issueForm.issueClassifyName = data.issueClassifyName;
  issueForm.issueType = data.issueType;
  issueForm.issueTypeName = data.issueTypeName;
  issueForm.assignId = data.assignId;
  issueForm.severity = data.severity;
  issueForm.priority = data.priority;
  issueForm.issueSource = data.issueSource;
  issueForm.customerId = data.customerId;
  issueForm.customerName = data.customerName;
  issueForm.projectManagerId = data.projectManagerId;
  issueForm.projectManagerName = data.projectManagerName;
  issueForm.contactorName = data.contactorName;
  issueForm.contactorTel = data.contactorTel;
  issueForm.title = data.title;
  issueForm.description = data.description;
  issueForm.status = data.status;
  issueForm.orgId = data.orgId;
  issueForm.expectFinishTime = data.expectFinishTime;
  issueForm.submitter = data.submitter;
  issueForm.submitTime = data.submitTime;

  const temp: any = proxy.$refs['refCkEditor'];
  if (isEmpty(issueForm.description)) {
    temp.setValue('');
  } else {
    temp.setValue(issueForm.description);
  }
}
</script>

<style lang="scss" scoped>
#issueApplyEditDiv {
  height: 100%;
  background-color: $base-white;  
  .form {
    width: 100%;
    height: 100%;
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
}
</style>